package com.epfresh.supplier.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.epfresh.api.dialog.AreaDialog;
import com.epfresh.api.entity.RequestEntitySupply;
import com.epfresh.api.entity.ResponseEntity;
import com.epfresh.api.global.BaseActivity;
import com.epfresh.api.global.BaseApplication;
import com.epfresh.api.http.OnRequestListener;
import com.epfresh.api.http.RequestManager;
import com.epfresh.api.utils.InputControl;
import com.epfresh.api.utils.ToastUtils;
import com.epfresh.api.utils.VerificationUtils;
import com.epfresh.supplier.R;
import com.epfresh.supplier.entity.City;
import com.epfresh.supplier.entity.CityAddressList;
import com.epfresh.supplier.entity.Flag;
import com.google.gson.Gson;

import java.util.HashMap;
import java.util.Map;

public class NewAddressActivity extends BaseActivity {

    static final String TAG = "NewAddressActivity";

    TextView areaTv;
    EditText detailEt;
    TextView sureBu;
    EditText nameEt;
    EditText phoneEt;
    EditText addressNameEt;
    String provinceId = "";
    String cityId = "";
    String districtId = "";
    String provinceName = "";
    String cityName = "";
    String districtName = "";
    String id = "";
    String accountId = "";
    String address = "";
    String contactName;
    String phone;
    String name;
    private String cityname;
    private boolean isEdit;

    String cmd = com.epfresh.api.constant.AppSupplyRouterConstant.cmd_store_store_pickUpAddress_add;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        tvBack.setVisibility(View.VISIBLE);
        ivBack.setVisibility(View.VISIBLE);
        toolbarTitle.setText("添加提货地址");
        setContentView(R.layout.activity_newaddress);
        areaTv = (TextView) findViewById(R.id.area);
        areaTv.setOnClickListener(this);
        detailEt = (EditText) findViewById(R.id.detail);
        sureBu = (TextView) findViewById(R.id.tv_btn);
        sureBu.setOnClickListener(this);
        phoneEt = (EditText) findViewById(R.id.phone);
        nameEt = (EditText) findViewById(R.id.name);
        addressNameEt = (EditText) findViewById(R.id.address_name);
        Intent intent = getIntent();
        id = intent.getStringExtra("id");
        if (id != null) {
            isEdit = true;
            provinceId = intent.getStringExtra("provinceId");
            cityId = intent.getStringExtra("cityId");
            districtId = intent.getStringExtra("districtId");
            cityId = intent.getStringExtra("cityId");
            provinceName = intent.getStringExtra("provinceName");
            cityName = intent.getStringExtra("cityName");
            districtName = intent.getStringExtra("districtName");
            accountId = intent.getStringExtra("accountId");
            address = intent.getStringExtra("address");
            name = intent.getStringExtra("name");
            phone = intent.getStringExtra("phone");
            contactName = intent.getStringExtra("contactName");
            nameEt.setText(contactName);
            addressNameEt.setText(name);
            if (name != null) {
                addressNameEt.setSelection(name.length() > 10 ? 10 : name.length());
            }
            phoneEt.setText(phone);
            toolbarTitle.setText("编辑地址");
            cmd = com.epfresh.api.constant.AppSupplyRouterConstant.cmd_store_store_pickUpAddress_modify;
            areaTv.setText(provinceName + cityName + districtName);
            detailEt.setText(address);
        }
/*        rightbtn.setText("保存");
        rightbtn.setVisibility(View.VISIBLE);*/
        phoneEt.addTextChangedListener(new TextWatcher() {
            int beforeLen = 0;
            int afterLen = 0;

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                beforeLen = s.length();
                phoneEt.setSelection(beforeLen);

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                afterLen = s.length();
            }

            @Override
            public void afterTextChanged(Editable s) {

                String tel = s.toString();
                //手机号
                if (tel.startsWith("1")) {
                    if (tel.length() > 11) {
                        s.delete(11, 12);
                    }
                } else if (tel.startsWith("0") && beforeLen < afterLen) {
                    if (tel.startsWith("01")) {
                        if (tel.length() == 2) {
                            tel = "010-";
                            s.insert(2, "0-");
                        }
                    } else if (tel.startsWith("02")) {
                        if (tel.length() == 3) {
                            s.insert(3, "-");
                        }
                    } else if (tel.length() == 4) {
                        s.insert(4, "-");
                    }

                } else if (tel.startsWith("0") && beforeLen > afterLen) {

                } else if (tel.startsWith("86")) {
                    s.delete(0, 2);
                } else if (tel.startsWith("+86")) {
                    s.delete(0, 3);
                } else {
                    s.clear();
                }

            }
        });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.area:
//                Intent edit = new Intent(getApplicationContext(),
//                        MainActivity.class);
//                edit.putExtra("provinceId", provinceId);
//                edit.putExtra("cityId", cityId);
//                edit.putExtra("districtId", districtId);
//                edit.putExtra("provinceName", provinceName);
//                edit.putExtra("cityName", cityName);
//                edit.putExtra("districtName", districtName);
//                startActivityForResult(edit, 1);
                openArea();
                break;
            case R.id.baseback:
                // 返回上一页
                finish();
                break;
            case R.id.tv_btn:
            case R.id.rightbtn:
                postSave();
                break;
        }
    }

    City cityData;

    public void openArea() {
        AreaDialog areaDialog = new AreaDialog(this);
        if (cityData == null)
            cityData = areaDialog.getCityData();
        areaDialog.setPositiveDismiss(true);
        areaDialog.setCurrentIndex(cityData, provinceId, cityId, districtId);
        ;
        areaDialog.setOnPositiveClickListener(new AreaDialog.OnPositiveClickListener() {

            @Override
            public void onPositiveClickListener(int index1, CityAddressList city1, int index2, CityAddressList city2, int index3, CityAddressList city3) {
//                if (city1 != null && city2 != null && city3 != null) {
//                    cityName = city1.getName() + city2.getName() + city3.getName();
//                    provinceId = city1.getCode();
//                    cityId = city2.getCode();
//                    districtId = city3.getCode();
//                    areaTv.setText(cityName);
//                }

                if (city1 != null) {
                    cityName = city1.getName();
                    provinceId = city1.getCode();
                }
                if (city1 != null && city2 != null) {
                    cityName = city1.getName() + city2.getName();
                    cityId = city2.getCode();
                }
                if (city1 != null && city2 != null && city3 != null) {
                    cityName = city1.getName() + city2.getName() + city3.getName();
                    districtId = city3.getCode();
                }
                areaTv.setText(cityName);
            }
        });
        areaDialog.show();
    }

    @Override
    protected void onActivityResult(int requestcode, int resultcode, Intent date) {
        super.onActivityResult(requestcode, resultcode, date);
        switch (resultcode) {
            case 1:
                // 回传城市名字 城市ID
                if (date != null) {
                    cityname = date.getExtras().getString("name");
                    provinceId = date.getStringExtra("provinceCode");
                    cityId = date.getStringExtra("cityCode");
                    districtId = date.getStringExtra("areaCode");
//                    areaTv.setText(cityname);
                    Log.i("just 测试", date.getStringExtra("provinceCode") + "," + date.getStringExtra("cityCode") + "," + date.getStringExtra("areaCode"));
                }
                break;
        }
    }

    void postSave() {
        String keys[] = {"id", "provinceId", "cityId",
                "districtId", "address",
                "name", "tel", "contactName"};
        if (InputControl.isEmpty(addressNameEt)) {
            ToastUtils.TextToast(this, "请填写提货点名称");
            return;
        }
        if (!VerificationUtils.isValid(addressNameEt.getText().toString())){
            toast(getString(R.string.illegal_input,"提货点名称"));
            return;
        }
        if (InputControl.isEmpty(areaTv)) {
            ToastUtils.TextToast(this, "请先选择区域");
            return;
        }
        if (InputControl.isEmpty(detailEt)) {
            ToastUtils.TextToast(this, "请先填写详细地址");
            return;
        }
        if (!VerificationUtils.isValid(detailEt.getText().toString())){
            toast(getString(R.string.illegal_input,"详细地址"));
            return;
        }

        if (InputControl.isEmpty(nameEt)) {
            ToastUtils.TextToast(this, "请填写联系人姓名");
            return;
        }
        if (!VerificationUtils.isValid(nameEt.getText().toString())){
            toast(getString(R.string.illegal_input,"联系人姓名"));
            return;
        }
        if (InputControl.isEmpty(phoneEt)) {
            ToastUtils.TextToast(this, "请填写联系电话");
            return;
        }
        if ( phoneEt.getText().toString().length() != 11){
            toast("请填写正确的手机号");
            return;
        }else if (!VerificationUtils.isTelPhone(phoneEt.getText().toString())){
            toast("请填写正确的联系电话");
            return;
        }
        String values[] = {id, provinceId, cityId,
                districtId, detailEt.getText().toString()
                , addressNameEt.getText().toString(), phoneEt.getText().toString(), nameEt.getText().toString()};

        RequestEntitySupply<Map<String, String>> data = new RequestEntitySupply<>();
        data.setCmd(cmd);
        data.setClientIdentifierCode(getAppApplication().getClientIdentifierCode());
        Map<String, String> map = new HashMap<>();
        for (int i = 0; i < values.length; i++) {
            map.put(keys[i], values[i]);
        }
        map.put("storeId",BaseApplication.getInstance().getStoreId());
        map.put("merchantId",BaseApplication.getInstance().getMerchantId());
        //data.setToken(getUser().getToken());
        data.setParameters(map);
        request(data, cmd, onRequestListener);
    }


    OnRequestListener<Flag> onRequestListener = new OnRequestListener<Flag>() {
        @Override
        public Flag jsonToObj(String responseStr) {
            return new Gson().fromJson(responseStr, Flag.class);
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {

        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {

        }

        @Override
        public void onStart(Object tag) {

        }

        @Override
        public void onResponse(ResponseEntity<Flag> response, Object tag) {
            Flag flag = response.getResponseElement();
            if (flag.isSuccess() == true) {
                if (!isEdit)
                    getUser().addDeliveryAddressCount();
                toast(BaseApplication.getDoc().getBeenSubmitted());
                finish();
            } else {

            }
        }
    };

    @Override
    protected void onDestroy() {
        RequestManager.getInstance().cancel(cmd);
        super.onDestroy();
    }

}
